package com.alm.handle.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alm.common.core.redis.RedisCache;
import com.alm.entity.DevLogin;
import com.alm.entity.GetWayUpLoadData;
import com.alm.entity.PasingByteModel;
import com.alm.handle.core.domain.entity.SysAreaInfo;
import com.alm.handle.core.domain.entity.SysDevInfo;
import com.alm.handle.core.domain.entity.rq.GetWayInfoRq;
import com.alm.handle.core.domain.entity.rq.JdqControlsRq;
import com.alm.handle.core.domain.entity.rs.GetWayUpEleDataRS;
import com.alm.handle.mapper.AlmGetWayDevCurrentDataMapper;
import com.alm.handle.mapper.SysAreaInfoMapper;
import com.alm.handle.mapper.SysDevInfoMapper;
import com.alm.handle.mq.ProxyCommandService;
import com.alm.handle.service.AlmGetWayDevCurrentDataService;
import com.alm.handle.service.AlmLableService;
import com.alm.handle.service.ISysAreaInfoService;
import com.alm.handle.service.ISysDevInfoService;
import com.alm.handle.util.*;
import com.alm.service.PasEleBusinessService;
import com.alm.service.PasPublicService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.alm.common.utils.PageUtils.startPage;

@Service
public class AlmGetWayDevCurrentDataServiceImpl implements AlmGetWayDevCurrentDataService {
    private final Logger logger = LoggerFactory.getLogger(AlmGetWayDevCurrentDataServiceImpl.class);

    @Resource
    private AlmGetWayDevCurrentDataMapper devCurrentDataMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private PasPublicService publicService;
    @Resource
    private SysDevInfoMapper sysDevInfoMapper;
    @Autowired
    private ISysDevInfoService infoService;
    @Autowired
    private PasEleBusinessService businessService;
    @Autowired
    private ISysAreaInfoService areaInfoService;
    @Resource
    private SysAreaInfoMapper areaInfoMapper;
    @Autowired
    private AlmLableService almLableService;
    @Override
    public void pasingGetWayData(String gwMac,GetWayUpLoadData upLoadData) {
        // 主要是更新缓存中的用电量信息，没有写入数据库
        //更新用电量信息
        try {
            String address=upLoadData.getAddress();
            JSONObject object = new JSONObject();
            JSONObject exJson = new JSONObject();
            businessService.getWaypaSingData(object, 2, upLoadData.getDevData(), exJson);
            GetWayUpEleDataRS newGwData = JSON.parseObject(object.toJSONString(),GetWayUpEleDataRS.class);
            //有序集合用来排序
            newGwData.setDevId(address);
            newGwData.setGetWayMac(gwMac);
            newGwData.computeData();
            String sort_key= SoketEleKey.GW_ELE_ZSET+gwMac;
            redisCache.addZset(sort_key,address,System.currentTimeMillis());
            String data_key= SoketEleKey.GW_ELE_DATA+gwMac;
            String redis_data=redisCache.getCacheMapValue(data_key,address);
            if(redis_data!=null&&!redis_data.equals("")){
                GetWayUpEleDataRS oldGwData=JSON.parseObject(redis_data,GetWayUpEleDataRS.class);
                newGwData= ELeCurrentUtil.resetDataByGW(oldGwData,newGwData);
            }
            newGwData.setUpdateTime(System.currentTimeMillis());
            redisCache.setCacheMapValue(data_key,address, JSON.toJSONString(newGwData));
        }catch (Exception e){
            logger.info("解析网关数据错误~  原数据:{}",upLoadData.getDevData());
        }

        //hash用来存储数据
    }

    @Override
    public void getWaylogin(PasingByteModel.Header header) throws Exception {
        DevLogin devLogin= publicService.devLogin(header);
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("device_id",header.getDvcId());
        queryWrapper.select("id");
        if(sysDevInfoMapper.selectOne(queryWrapper)==null){
            infoService.insertDevInfo(header,devLogin);
        }
        infoService.updataStatus(header.getDvcId());
        redisCache.setCacheObject(SoketEleKey.ON_LINE+header.getDvcId(),
                "1",60, TimeUnit.SECONDS);
//
//        if(bo){
//            Integer id= eventsLogService.isnertLog(header.getDvcId(),4);
//            eventsLogService.upexistTime(header.getDvcId(),4,id);
//        }else{
//            Integer id= eventsLogService.isnertLog(header.getDvcId(),1);
//            eventsLogService.upexistTime(header.getDvcId(),1,id);
//        }
//
//        // 将登录记录存到数据库
//        setDataBaseByDevLoginInfo(header, devLogin);
    }

    @Override
    public List<SysDevInfo> queryListByRq(GetWayInfoRq getWayInfoRq)   {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (getWayInfoRq.getAreaId() != null && getWayInfoRq.getAreaId().trim().length()> 1) {
            queryWrapper.eq("menu_id", getWayInfoRq.getAreaId());
            SysAreaInfo sysAreaInfo = areaInfoMapper.selectOne(queryWrapper);
            if (sysAreaInfo != null ) {
                areaInfoService.findAllChild(sysAreaInfo);
            }
            sysAreaInfo.setChildIds(getWayInfoRq.getAreaId());
            getWayInfoRq.setAreaId(sysAreaInfo.getChildIds());
        }else{
            getWayInfoRq.setAreaId(null);
        }
        startPage();
        List<SysDevInfo> list = infoService.queryListByRq(getWayInfoRq);
        return list;
    }

    @Override
    public Boolean sendJdqControlsRq(JdqControlsRq jdqControlsRq) {
        StringBuffer tc_data=new StringBuffer("");
        List<Integer> check_number = Arrays.asList(1, 2, 3, 4);
        for (int i = 0; i < check_number.size(); i++) {
            if(jdqControlsRq.getControld()==1){
                if(jdqControlsRq.getLineIdList().contains(check_number.get(i))){
                    tc_data.append("01");
                }
            }else{
                if(jdqControlsRq.getLineIdList().contains(check_number.get(i))){
                    tc_data.append("00");
                }
            }
        }
        byte [] suuidByte= ByteUtils.hexStrToBytes("FEF0");
        byte [] uuidByte= ByteUtils.hexStrToBytes("FE40");
        byte [] data= transparencyTransmission(jdqControlsRq.getGwMac(),
                tc_data.toString(),jdqControlsRq.getDevMac(),suuidByte,uuidByte
        );
        System.out.println(ByteUtils.bytesToString(data));
        return  SendMessage.sendMessage(data, jdqControlsRq.getGwMac().toUpperCase());
    }

    @Override
    public void deal_lable(PasingByteModel.Header header) {
        Integer inType=header.getIntData().get(6).intValue();
        switch (inType){
            case 0x10:
                almLableService.deal_lable_status(header);
                break;
            case 0x30:
                almLableService.deal_lable_business(header);
                break;
            case 0x04:
                break;
            case 0x42:
                break;
        }
    }


    // 2024.05.25 这里是把Override注解加上了
    @Override
    public byte[] transparencyTransmission(String devid, String tcData, String mac, byte[] sUuid, byte [] uUuid) {
        int tcid= (int) (1+Math.random()*(254-1+1));
        byte[] configData=getSensitivityConfigData(sUuid,uUuid,mac,tcid, tcData);
        ByteBuf befor= InstructionByteUtils.getBFBYTEInstruction(devid,
                (short) 128,(short)0);
        byte[] after=InstructionByteUtils.getBYTEISData(0x5743,
              128 ,
                Integer.parseInt("90",16),//数据体
                configData,0x008A);
        byte [] inBytes= InstructionByteUtils.getBYTEISBYTES(befor,after);
        return inBytes;
    }
    private byte[] getSensitivityConfigData(byte[] sUuid,byte [] uUuid,String arrdes,
                                            Integer tcid,String data){
        ByteBuf buf= Unpooled.buffer(1);
        buf.writeByte(0x10); //固定值
        buf.writeByte(tcid); //
        buf.writeShort(0x01);
        buf.writeBytes(
                InstructionByteUtils.getToZeroByArray(
                        InstructionByteUtils.toByteArray(Long.parseLong(arrdes,16)
                        )));
        buf.writeByte(0x20);// 连接超时时间
        buf.writeByte(0x03);//  设定该时间内没有通信 则断开连接
        buf.writeByte(0x01);//写入
        buf.writeByte(sUuid.length);
        buf.writeBytes(sUuid);
        buf.writeByte(uUuid.length);
        buf.writeBytes(uUuid);
        byte[] bytedata= ByteUtils.hexStrToBytes(data);
        buf.writeByte(bytedata.length);
        buf.writeBytes(bytedata);
        byte [] databytes=new byte[buf.readableBytes()];
        buf.readBytes( databytes);
        buf.release();
        return databytes;
    }
}
